package com.atguigu.aiproject.controller.ai;

import com.atguigu.aiproject.entity.Result;
import com.atguigu.aiproject.service.UserService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/ai/analysis")
public class AnalysisController {
    @Autowired
    @Qualifier("pdfClient") //按函数名称获取
    private ChatClient pdfClient;

    public static class Request {
        public String question;
    }
    @Autowired
    @Qualifier("pdfVectorStore")
    private VectorStore vectorStore;
    @PostMapping("/pdf/upload")
    public Result<?> pdfUpload(@RequestParam(name = "file") MultipartFile uploadFile) throws IOException {
        // 获取运行路径 (当前工作目录)
        final String runningPath = System.getProperty("user.dir");
        if (uploadFile.isEmpty()) return Result.error("上传失败");
        //判断文件是否存在
        File ff = new File(runningPath, uploadFile.getOriginalFilename() + ".json");
        if (ff.exists()) {
            ((SimpleVectorStore) vectorStore).load(ff);//存在文件，直接上传json文件
            return Result.success("上传成功");
        }
        String filepath = uploadFile.getOriginalFilename();// 上传到该文件夹
        File destFile = new File(runningPath, filepath); // 使用运行路径
        uploadFile.transferTo(destFile);
        // 切片
        PagePdfDocumentReader pdfReader = new PagePdfDocumentReader(new FileSystemResource(destFile),
                PdfDocumentReaderConfig.builder()
                        .withPageTopMargin(0)
                        .withPageExtractedTextFormatter(ExtractedTextFormatter.builder()
                                .withNumberOfTopTextLinesToDelete(0)
                                .build())
                        .withPagesPerDocument(1)
                        .build());

        List<Document> documentList = pdfReader.read();
        for (Document document : documentList) {
            System.out.println(document.getText());
            System.out.println("--------------------------------------------");
        }
        // 保存到向量数据库
        vectorStore.add(documentList);
        //将向量数据库内容存到本地
        ((SimpleVectorStore) vectorStore).save(new File(runningPath, uploadFile.getOriginalFilename() + ".json"));

        return Result.success("上传成功");
    }

    @PostMapping(value = "/pdf/query", produces = "text/event-stream;charset=utf-8")
    public Flux<String> pdfQuery(@RequestBody Request request) {
        String question = request.question;
        // 1. 参数校验
        if (question == null || question.isBlank()) {
            throw new RuntimeException("问题不能为空");
        }
        return pdfClient.prompt()
                .user(question)
                .stream()
                .content();
    }
}
